package com.ruoyi.wx.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.wx.domain.PtExpVideo;
import com.ruoyi.wx.domain.PtReport;
import com.ruoyi.wx.domain.PtScore;
import com.ruoyi.wx.mapper.PtExpVideoMapper;
import com.ruoyi.wx.mapper.PtScoreMapper;
import com.ruoyi.wx.service.IPtExpVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.wx.service.IPtReportService;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author moxiu
 * @since 2021-11-13
 */
@Service
public class PtExpVideoServiceImpl extends ServiceImpl<PtExpVideoMapper, PtExpVideo> implements IPtExpVideoService {

	@Autowired
	private PtScoreMapper ptScoreMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void recordWatch(Long videoId,Long expId) {
		final Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
		final PtScore ptScore = ptScoreMapper.selectExist(userId, expId);
		if (ptScore == null) {
			//如果成绩卡为空 则 创建当前用户的实验卡
			PtScore createScore = new PtScore();
			createScore.setExpId(expId);
			createScore.setStuId(userId);
			createScore.setCreateTime(LocalDateTime.now());
			ptScoreMapper.insert(createScore);
		}
		//记录用户看的视频
		String s1 = ptScoreMapper.selectVideoList(userId,expId);
		String s = null;
		int a = Math.toIntExact(videoId);
		if (s1 == null) {
			Set<Integer> set = new HashSet<>();
			set.add(a);
			s = JSONObject.toJSONString(set);
		}else {
			List<Integer> parse = (List<Integer>)JSONObject.parse(s1);
			Set<Integer> result = new HashSet<>(parse);
			result.add(a);
			s = JSONObject.toJSONString(result);
		}
		//更新用户所看视频的id集合
		ptScoreMapper.update(null,Wrappers.lambdaUpdate(new PtScore())
			.eq(PtScore::getExpId,expId).eq(PtScore::getStuId,userId)
			.set(PtScore::getUpdateTime, LocalDateTime.now())
			.set(PtScore::getVideoList,s)
		);
	}

	@Override
	public List<Integer> selectAllVideo(Long userId,Long expId) {
		PtScore ptScore = ptScoreMapper.selectOne(Wrappers.lambdaQuery(PtScore.class)
			.eq(PtScore::getStuId, userId).eq(PtScore::getExpId, expId)
			.select(PtScore::getVideoList)
		);
		if (ptScore == null) {
			return null;
		}
		List<Integer> parse = (List<Integer>)JSONObject.parse(ptScore.getVideoList());
		return parse;
	}
}
